package com.piesat.quake.business.device.mqtt.writer;

import com.piesat.quake.business.device.mqtt.NumberType;
import com.piesat.quake.business.device.mqtt.param.NumberParseParam;
import com.piesat.quake.business.device.mqtt.param.ParseParam;

import io.netty.buffer.ByteBuf;

import static com.piesat.quake.business.device.mqtt.reader.NumberReader.LITTLE_ENDIAN;

/**
 * 数字类型写入器
 *
 * @author Gersy
 * @date 2023/2/6
 * @since 1.0
 */
public class NumberWriter implements Writer {

    @Override
    public void write(ByteBuf byteBuf, ParseParam numberParam, Object value) {
        NumberParseParam param = (NumberParseParam) numberParam;
        int type = param.numberType;
        if (type == NumberType.BYTE) {//byte
            byteBuf.writeByte((byte) value);
        } else if (type == NumberType.INT) {//int
            if (param.endian == LITTLE_ENDIAN) {
                byteBuf.writeIntLE((int) value);
            } else {
                byteBuf.writeInt((int) value);
            }
        } else if (type == NumberType.FLOAT) {//float
            if (param.endian == LITTLE_ENDIAN) {
                byteBuf.writeFloatLE((float) value);
            } else {
                byteBuf.writeFloat((float) value);
            }
        } else if (type == NumberType.SHORT) {//short
            if (param.endian == LITTLE_ENDIAN) {
                byteBuf.writeShortLE((short) value);
            } else {
                byteBuf.writeShort((short) value);
            }
        } else if (type == NumberType.LONG) {//long
            if (param.endian == LITTLE_ENDIAN) {
                byteBuf.writeLongLE((Long) value);
            } else {
                byteBuf.writeLong((Long) value);
            }
        } else if (type == NumberType.DOUBLE) {//double
            if (param.endian == LITTLE_ENDIAN) {
                byteBuf.writeDoubleLE((Double) value);
            } else {
                byteBuf.writeDouble((Double) value);
            }
        }
    }
}
